package fr.mmt.gisfizz.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * User. <br/>
 *
 * @author Mathieu MAST
 */
@Entity
@Table(name = "user")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User extends AbstractEntity implements UserDetails, Serializable {

    @Column(name = "login", unique = true)
    @Getter
    @Setter
    private String login;
    @Column(name = "displayname")
    @Getter
    @Setter
    String displayname;
    @Column(name = "password")
    @Getter
    @Setter
    String password;
    @ManyToMany(fetch = FetchType.EAGER)
    @Getter
    @Setter
    List<Role> roles;

    @Override
    public String getUsername() {
        return login;
    }

    @Override
    public String toString() {
        return login + " (" + displayname + ")";
    }

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();
        if (null != roles) {
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority(role.getCode()));
            }
        }
        return authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
